import { Component, Injector, ViewChild } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { WorkFlowManagerServiceProxy, PagedMangerPaperInput, PaperState } from '@shared/service-proxies/service-proxies';
import { Paginator } from 'primeng/paginator';
import { Table } from 'primeng/table';
import { finalize } from 'rxjs/operators';
import { LazyLoadEvent } from 'primeng/api';
import { map as _map } from 'lodash-es';
import { DateTime } from 'luxon';
import { DateTimeService } from '@app/shared/common/timing/date-time.service';
import { TabDirective } from 'ngx-bootstrap/tabs';
import { WorkflowDetailComponent } from '@app/main/workflow/workflow-detail.component';
import { WorkflowManagerDetailComponent } from './workflow-manager-detail.component';
import { IBackWorkFlowListData } from '@app/shared/common/workflow/workflow-common-interface';

@Component({
    templateUrl: './workflow-manager.component.html',
    animations: [appModuleAnimation()]
})
export class WorkflowManagerComponent extends AppComponentBase {

    @ViewChild('dataTable', { static: true }) dataTable: Table;
    @ViewChild('paginator', { static: true }) paginator: Paginator;
    @ViewChild('workFlowDetail', { static: true }) workflowDetailModal: WorkflowDetailComponent;
    @ViewChild('WorkflowManagerDetail', { static: true }) WorkflowManagerDetail: WorkflowManagerDetailComponent

    loading = false;

    adminPermission: boolean = false;

    actionNames:any;
    units = [];

    filterText = '';

    pagedPaperParam: PagedMangerPaperInput = new PagedMangerPaperInput();

    public dateRange: DateTime[] = [this._dateTimeService.getStartOfDayMinusDays(30), this._dateTimeService.getEndOfDay()];

    constructor(
        injector: Injector,
        private _workFlowManagerService: WorkFlowManagerServiceProxy,
        private _dateTimeService: DateTimeService
    ) {
        super(injector);

        this.adminPermission = this.isGranted('Pages.Manage.WorkFlow.Admin');
        this.actionNames = [
            { name: '执行中', paperState: 1, isShow: true },
            { name: '已办结', paperState: 2, isShow: true },
            { name: '已作废', paperState: 3, isShow: this.adminPermission },
            { name: '草稿箱', paperState: 0, isShow: this.adminPermission }
        ];

        this.pagedPaperParam.unitId = 0;
        this.pagedPaperParam.paperState = PaperState.Running;

        // if ($stateParams.wfId) {
        //     vm.requestParams.inclusiveWorkFlowId = [$stateParams.wfId];
        // }
    }

    ngOnInit() {
        this.init();
    }
    ngAfterViewInit(): void {
        this.primengTableHelper.adjustScroll(this.dataTable);
    }

    private init() {
            /*
            userRoleUnitSelectionService.getAllLv1Units({}).then(function (result) {
                vm.units = result.data;
                vm.units.unshift({ code: "", displayName: "请选择" });
            });*/

            /*
            unitSelectionHelper.getLeaveUnitSelectionData(function (units) {
                if (units) vm.units = units;
                vm.units.unshift({ id: 0, displayName: "请选择" });
            });*/
    }

   
    getListData(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            if (this.primengTableHelper.TryChangePage(this.paginator, 0)) {
                return;
            }
        }
        this.primengTableHelper.showLoadingIndicator();

        this.pagedPaperParam.startDate = this.dateRange[0];
        this.pagedPaperParam.endDate = this.dateRange[1];
        this.pagedPaperParam.sorting = this.primengTableHelper.getSorting(this.dataTable);
        this.pagedPaperParam.maxResultCount = this.primengTableHelper.getMaxResultCount(this.paginator, event);
        this.pagedPaperParam.skipCount = this.primengTableHelper.getSkipCount(this.paginator, event);

        this._workFlowManagerService.getPagedPapers(this.pagedPaperParam)
        .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
        .subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
            this.primengTableHelper.hideLoadingIndicator();
        });
    }

    delete(paperId: string): void {
        this.message.confirm(this.l('DeleteWarningMessage'), this.l('AreYouSure'),
        (isConfirmed) => {
          if (!isConfirmed) return;
          this.loading = true;
          this._workFlowManagerService.superDelete([paperId])
            .pipe(finalize(() =>  this.loading = false))
            .subscribe(() => {
              this.reloadPage();
              this.notify.success(this.l('SuccessfullyDeleted'));
            });
        })
    }

    reloadPage(): void {
        if (this.primengTableHelper.TryChangePage(this.paginator, this.paginator.getPage())) {
            return;
        }

        this.getListData(null);
    }

    backToList(item?: IBackWorkFlowListData) {
        if (item && item.isReload) {
            this.reloadPage();
        }
    }
    
    private changeTab(index: number) {
        this.pagedPaperParam.paperState = this.actionNames[index].paperState;
        if (this.primengTableHelper.TryChangePage(this.paginator, 0)) {
            return;
        }

        this.getListData(null);
    }

    onTabSelect(data: TabDirective, index: number) {
        this.changeTab(index);
    }

    goDetailModel(paperId: string) {
        if (this.adminPermission) {
            this.WorkflowManagerDetail.show({paperId: paperId});
        }else{
           this.workflowDetailModal.show({paperId: paperId});
        }
    }
}
